package com.health.system.security.auth;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.health.system.convert.UserConvert;
import com.health.system.entity.Role;
import com.health.system.entity.UserAuth;
import com.health.system.entity.UserInfo;
import com.health.system.mapper.RoleMapper;
import com.health.system.mapper.UserAuthMapper;
import com.health.system.mapper.UserInfoMapper;
import com.health.system.security.auth.entity.HealthSecurityAuthDetails;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 用户登录认证
 *
 */
@Service
public class BlogUserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserAuthMapper userAuthMapper;
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private UserInfoMapper infoMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 获取用户
        UserAuth userAuth = userAuthMapper.selectOne(
                new LambdaQueryWrapper<UserAuth>().eq(UserAuth::getUsername, username));
        if (userAuth == null) {
            throw new UsernameNotFoundException("不存在该用户");
        }
        UserConvert userConvert = UserConvert.INSTANCE;
        HealthSecurityAuthDetails details = userConvert.convert(userAuth);

        List<Role> roles = roleMapper.findRoleByUserId(userAuth.getId());
        details.setRoles(roles);

        String nickname = infoMapper.selectOne(new LambdaQueryWrapper<UserInfo>()
                .eq(UserInfo::getId, details.getUserInfoId()).select(UserInfo::getNickname)).getNickname();
        details.setNickName(nickname);

        return details;
    }
}
